package cn.hxth.cloud.provider.updater;

import cn.hxth.cloud.api.common.util.DateProvider;
import cn.hxth.cloud.api.domain.Product;
import cn.hxth.cloud.api.mapper.ProductMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

public abstract class  AbstractProductUpdaterFactory<T> implements ProductUpdaterFactory<T> {
    private Logger logger = LoggerFactory.getLogger(AbstractProductUpdaterFactory.class) ;
    protected DateProvider dateProvider ;
    protected ProductMapper productMapper ;

    public AbstractProductUpdaterFactory(DateProvider dateProvider, ProductMapper productMapper) {
        this.dateProvider = dateProvider;
        this.productMapper = productMapper;
    }

    @Override
    public ProductUpdater create(T parameter) {
        try{
            List<Long> ids = this.getProductIds(parameter);
            List<Product> products = this.createProducts(ids);
            return  this.createProductUpdater(products,parameter) ;
        }catch (Exception e){
        logger.error("error",e);
        return  null ;
        }


    }
    protected abstract List<Long> getProductIds(T parameter) throws Exception ;
    protected abstract ProductUpdater createProductUpdater(List<Product> products,T parameter)throws Exception ;
    private List<Product> createProducts( List<Long> ids)throws Exception{
        List<Product> products = new ArrayList<>(ids.size()) ;
        for(long id:ids){
            Product product = this.productMapper.selectByPrimaryKey(id);
            products.add(product) ;
        }
        return  products ;
    }
}
